/**
 * Created by xc on 2017/11/21.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var YjxBaseModel = require('./YjxBaseModel');
var async  = require( 'async'); // 同步控制

//--------------------------------------------------------------------------------------
// Schema 结构
var YjxTradeOrderModel = function(obj){
    YjxBaseModel.call(this,obj);

    // 以下为表定义数据，需要的字段就填入
    //`order_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '订单id',
    //`order_no` varchar(50) NOT NULL DEFAULT '' COMMENT 'itb自定义订单号',
    //`pay_order_no` varchar(50) NOT NULL COMMENT 'itb自定义订单号:支付用',
    //`detail_cnt` int(8) NOT NULL DEFAULT '0' COMMENT '子订单数',
    //`device` int(8) NOT NULL DEFAULT '0' COMMENT '见接口定义中的device',
    //`state` int(3) NOT NULL DEFAULT '0' COMMENT '订单状态:10待支付、11已支付、12支付失败、20制作中、30配送中、40完成、50取消',
    //`inv_id` bigint(20) DEFAULT NULL COMMENT '发票id，为null表示未开票',
    //`partner_id` bigint(20) NOT NULL DEFAULT '0' COMMENT '合作平台[保留字段]，如紫云',
    //`pay_platform` int(3) NOT NULL DEFAULT '0' COMMENT '支付平台: 10微信, 20支付宝',
    //`total_fee` bigint(12) NOT NULL DEFAULT '0' COMMENT '订单总金额（单位为rmb分）实际支付金额',
    //`coupon_fee` bigint(12) NOT NULL DEFAULT '0' COMMENT '子项：优惠费（单位为rmb分），实际优惠金额(<=优惠券discount)',
    //`coupon_id` bigint(20) DEFAULT NULL COMMENT '优惠券id',
    //`addr_id` bigint(20) DEFAULT NULL COMMENT '收件地址id [保留字段]',
    //`express_type` int(3) NOT NULL DEFAULT '10' COMMENT '配送方式 [保留字段]: 10预付邮费, 20到付邮费',
    //`user_id` bigint(20) DEFAULT NULL COMMENT '用户id',
    //`odr_dtl_type_tag` bigint(20) NOT NULL DEFAULT '0' COMMENT '子订单类型标记位(多子订单时按位与,即累加,同类型不重复累加): \n2[去水印订单],4[秒杀订单],8[vip订单],16[待定]',
    //`odr_type` int(3) NOT NULL DEFAULT '0' COMMENT '订单类型: 0常规, 20:原始秒杀订单',
    //`hide` int(1) NOT NULL DEFAULT '0' COMMENT '0:订单列表中正常显示, 1:订单列表中不显示',
    //`desc` varchar(200) DEFAULT NULL COMMENT '订单描述',
    //`finish_time` datetime DEFAULT NULL COMMENT '订单完成时间',
    //`create_time` datetime NOT NULL,
    //`update_time` datetime NOT NULL,
    //`update_by` varchar(50) NOT NULL,
    //`del_flg` int(1) NOT NULL DEFAULT '0',

};

YjxTradeOrderModel.prototype = new YjxBaseModel();

// 取得表名
YjxTradeOrderModel.prototype.getTableName = function(){
    return 'yjx_trade_order';
};
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
YjxTradeOrderModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'order_id='+this.order_id;
};


//--------------------------------------------------------------------------------------
// 获取订单基本信息(含支付信息)
YjxTradeOrderModel.prototype.getOrderInfoWithPayInfo = function(orderId, callback){
    var THIS = this;

    pool.pool.getConnection(function(err, connection) {

        var sql = ' SELECT o.*, '+
            ' p.his_id AS pay_his_id, '+
            ' CASE WHEN p.pay_platform=10 THEN p.pay_info21 '+
            '      WHEN p.pay_platform=30 THEN p.pay_info4 '+
            '      ELSE NULL END AS transaction_id '+
            ' FROM yjx.yjx_trade_order o '+
            ' LEFT JOIN yjx.yjx_payment_his p '+
            ' ON p.del_flg=0 AND p.trade_obj_id=o.order_id AND p.trade_obj_no=o.order_no '+
            ' WHERE o.del_flg=0 AND o.order_id='+orderId;

        console.log(sql);
        connection.query(sql, function (error, result) {
            if (error) {
                console.log('YjxTradeOrderModel [getOrderInfoWithPayInfo] Error: ' + error);
            }
            connection.release();

            callback(error, result);
        });
    });
};


/**
 * 获取总订单sql 数量/列表 sql(多子订单时按位与,即累加): 2[去水印订单],4[秒杀订单],8[vip订单],16[待定]
 *
 * @author 毛凯
 * @date 2017-11-20
 *
 * @param bForCnt 标识位，true代表查询总条数sql,false查询数据sql
 * @param userId 用户唯一标识
 * @param pageNum 页数
 * @param pageSize 每页显示个数
 * @param payType 支付方式
 * @param state 订单状态:10待支付、11已支付、12支付失败、20制作中、30配送中、40完成、50取消
 * @return 对应的sql
 *
 **/
function findOrderSql(bForCnt,userId,pageNum,pageSize,state,payType){
    var sql = "";
    if(bForCnt) {
        sql += "SELECT COUNT(0) as count "
    } else {
        sql += "SELECT	" +
            "	  yto.order_id AS id,	" +
            "	  yto.odr_type AS `type`,	" +
            "     yto.order_no AS no,    "  +
            "	  yto.state AS state,	" +
            "	  yto.desc AS `name`,	" +
            "	  yto.total_fee AS totalFee,	" +
            "     yto.total_cost_pts AS totalPoints ," +
            "     yto.discount_fee AS discountFee ," +
            "     yto.coupon_fee AS couponFee ," +
            "     yto.pay_type AS payType ," +
            "	  DATE_FORMAT(	" +
            "	    yto.finish_time,	" +
            "	    '%Y-%m-%d %H:%i:%S'	" +
            "	  ) AS doneTime,	" +
            "	  yto.odr_dtl_type_tag ," +
            "	  DATE_FORMAT(	" +
            "        yto.create_time,   " +
            "	    '%Y-%m-%d %H:%i:%S'	" +
            "	  ) AS createTime 	" ;
    }
    sql += "	FROM	" +
            "	  yjx.yjx_trade_order yto	" +
            "	WHERE yto.user_id = " + userId + "	" +
            "     AND yto.state in ( " + state + ") " +
            "	  AND yto.hide = 0	" +
            "	  AND yto.del_flg = 0	" +
            "     AND yto.pay_type in ("+payType+")  " +
            "   ORDER BY yto.create_time DESC ";
    if(!bForCnt){
        if (typeof pageNum !== 'undefined' && pageNum !== null &&
            typeof pageSize !== 'undefined' && pageSize !== null) {
            var skipCnt = Number(pageNum || '0') * Number(pageSize || '0');
            sql += " LIMIT " + skipCnt + "," + Number(pageSize || '0');
        }
    }
    return sql;
}

/**
 * 获取用户去水印子订单列表
 *
 * @author 毛凯
 * @date 2017-11-18
 *
 * @param  orderId	订单总表的主键
 * @param  callback 回调
 *              err 错误信息
 *              result 查询后返回结果
 **/
YjxTradeOrderModel.prototype.getUserWMOrderSubOrderList = function(orderId,callback){

    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxTradeOrderModel.js [getUserWMOrderSubOrderList] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql = ' SELECT dud.doc_name AS docName, ' +
            '        wm.order_id AS id, ' +
            '        wm.desc AS itemDesc, ' +
            '        wm.unit, ' +
            '        wm.qty, ' +
            '        tdd.design_name AS itemName, ' +
            '        tdp.thumb AS itemThumb, ' +
            '        dud.uni_doc_id AS docId, ' +
            '        dup.thumb AS thumb, ' +
            '        dud.create_time AS `time`, ' +
            '        "1" AS opType ' +
        ' FROM yjx.yjx_trade_odr_dtl_wm wm, ' +
        '      itbour.tg_type tt,    ' +
        '      yjx.yjx_uni_user_doc uud, ' +
        '      itbour.tg_design_doc tdd, ' +
        '      yjx.yjx_design_user_doc dud ' +
        ' LEFT JOIN yjx.yjx_design_user_page dup ON dud.doc_id = dup.doc_id ' +
        ' AND dup.page_index = 0 ' +
        ' AND dup.del_flg = 0 ' +
        ' LEFT JOIN itbour.tg_design_page tdp ON dud.design_id = tdp.design_id ' +
        ' AND tdp.page_index = 0 ' +
        ' AND tdp.del_flg = 0 ' +
        ' WHERE wm.order_id = ' + orderId +
        '   AND wm.uni_doc_id = uud.uni_doc_id ' +
        '   AND uud.uni_doc_id = dud.uni_doc_id ' +
        '   AND tdd.design_id = dud.design_id ' +
        '   AND dud.type_id = tt.type_id ' +
        '   AND tt.top_parent <> 1030 ' +
        '   AND tt.del_flg = 0 ' +
        '   AND wm.del_flg = 0 ' +
        ' UNION ALL ' +
        ' SELECT vud.doc_name AS docName, ' +
        '        wm.order_id AS id, ' +
        '        wm.desc AS itemDesc, ' +
        '        wm.unit, ' +
        '        wm.qty, ' +
        '        vdd.design_name AS itemName, ' +
        '        vdd.theme_thumb AS itemThumb, ' +
        '        vud.doc_id AS docId, ' +
        '        vdd.theme_thumb AS thumb,' +
        '        vud.create_time AS `time`, ' +
        '        "2" AS opType ' +
        ' FROM yjx.yjx_trade_odr_dtl_wm wm, ' +
        '      yjx.yjx_uni_user_doc uud, ' +
        '      yjx.yjx_video_user_doc vud, ' +
        '      itbour.video_design_doc vdd ' +
        ' WHERE wm.order_id = ' + orderId +
        '   AND wm.uni_doc_id = uud.uni_doc_id ' +
        '   AND uud.uni_doc_id = vud.uni_doc_id ' +
        '   AND vud.design_id = vdd.design_id ' +
        '   ORDER BY `time` DESC ';
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxTradeOrderModel.js [getUserWMOrderSubOrderList] queryErr' + queryErr)
            }
            return callback(queryErr, results);
        });
    });



};

/**
 * 获取用户秒杀子订单列表
 *
 * @author 毛凯
 * @date 2017-11-18
 *
 * @param  orderId	订单总表的主键
 * @param  callback 回调
 *              err 错误信息
 *              result 查询后返回结果
 **/
YjxTradeOrderModel.prototype.getUserSKOrderSubOrderList = function(orderId,callback){

    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxTradeOrderModel.js [getUserSKOrderSubOrderList] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql =" SELECT  " +
            "    ods.detail_id AS id, " +
            "    ods.qty, " +
            "    ods.desc, " +
            "    11 AS `type`, " +
            "    ods.unit, " +
            "    ods.desc AS itemDesc, " +
            "    '' AS ppName, " +
            "    ods.uni_item_id, " +
            "    yui.item_id, " +
            "    tdd.design_id AS id, " +
            "    tdd.design_name AS itemName, " +
            "    tdp.thumb AS itemThumb, " +
            "    tdp.create_time AS `time` " +
            "  FROM " +
            "    yjx.yjx_trade_odr_dtl_sk ods, " +
            "    yjx.yjx_uni_items yui, " +
            "    itbour.tg_design_page tdp, " +
            "    itbour.tg_design_doc tdd " +
            "  WHERE ods.order_id = "+orderId+"  " +
            "    AND ods.uni_item_id = yui.uni_item_id " +
            "    AND tdd.design_id = yui.item_id " +
            "    AND tdp.design_id = tdd.design_id " +
            "    AND yui.del_flg = 0 " +
            "    AND tdp.page_index = 0 " +
            "    AND tdp.del_flg = 0 " +
            "  UNION ALL " +
            "  SELECT " +
            "    ods.detail_id AS id, " +
            "    ods.qty, " +
            "    ods.desc, " +
            "    11 AS `type`, " +
            "    ods.unit, " +
            "    ods.desc AS itemDesc, " +
            "    '' AS ppName, " +
            "    ods.uni_item_id, " +
            "    yui.item_id, " +
            "    vdd.design_id AS id, " +
            "    vdd.design_name AS itemName, " +
            "    vdd.theme_thumb AS itemThumb, " +
            "    vdd.create_time AS `time` " +
            "  FROM " +
            "    yjx.yjx_trade_odr_dtl_sk ods, " +
            "    yjx.yjx_uni_items yui, " +
            "    itbour.video_design_doc vdd " +
            "  WHERE ods.order_id = "+orderId+"  " +
            "    AND ods.uni_item_id = yui.uni_item_id " +
            "    AND vdd.design_id = yui.item_id " +
            "    AND yui.del_flg = 0 " +
            "    ORDER BY `time` DESC " ;
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxTradeOrderModel.js [getUserSKOrderSubOrderList] queryErr' + queryErr)
            }
            return callback(queryErr, results);
        });
    });



};

/**
 * 获取用户去vip子订单列表
 *
 * @author 毛凯
 * @date 2017-11-18
 *
 * @param  orderId	订单总表的主键
 * @param  callback 回调
 *              err 错误信息
 *              result 查询后返回结果
 **/
YjxTradeOrderModel.prototype.getUserVIPOrderSubOrderList = function(orderId,callback){

    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxTradeOrderModel.js [getUserVIPOrderSubOrderList] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql ="	SELECT	" +
            "	  vip.detail_id AS id,	" +
            "	  vip.detail_no AS `no`,	" +
            "	  yg.goods_type AS `type`,	" +
            "	  yg.goods_name AS itemName,	" +
            "	  yg.desc AS itemDesc,	" +
            "	  yg.theme_thumb AS itemThumb,	" +
            "	  '' AS ppName,	" +
            "	  yg.goods_id AS docId,	" +
            "	  vip.qty,	" +
            "	  '' AS thumnb,	" +
            "	  '' AS docName,	" +
            "	  vip.unit,	" +
            "	  vip.update_time	" +
            "	FROM	" +
            "	  yjx.yjx_trade_odr_dtl_vip vip,	" +
            "	  yjx.yjx_uni_items yui,	" +
            "	  yjx.yjx_goods  yg	" +
            "	WHERE vip.order_id = "+orderId+" " +
            "	  AND vip.uni_item_id = yui.uni_item_id	" +
            "	  AND yui.item_id = yg.goods_id	" +
            "	  AND vip.del_flg = 0 	" +
            "	  AND yg.del_flg = 0	" +
            "	  AND yui.del_flg = 0	" ;
            console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxTradeOrderModel.js [getUserVIPOrderSubOrderList] queryErr' + queryErr)
            }
            return callback(queryErr, results);
        });
    });
};

/**
 * 获取vip子订单列表
 * @author xc
 * @param  userId 用户的唯一标识
 * @param  orderId	订单总表的主键
 * @param  callback 回调
 **/
YjxTradeOrderModel.prototype.getVipOdrDtlList = function(userId, orderId, callback){

    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxTradeOrderModel.js [getVipOdrDtlList] getConErr' + getConErr);
            return callback(getConErr, null);
        }

        var sql =" SELECT t.*, p.`unit` AS p_unit, p.`qty` AS p_qty " +
            " FROM yjx.yjx_trade_odr_dtl_vip t " +
            "     ,yjx.yjx_trade_order o " +
            "     ,yjx.yjx_price p " +
            " WHERE t.del_flg=0 AND t.order_id=" +orderId+
            " AND o.del_flg=0 AND o.user_id=" +userId+
            " AND o.order_id=t.order_id " +
            " AND p.del_flg=0 AND p.state=10 " +
            " AND p.price_id=t.price_id " +
            " ORDER BY t.detail_id ";

        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxTradeOrderModel.js [getVipOdrDtlList] queryErr' + queryErr)
            }
            return callback(queryErr, results);
        });
    });
};

/**
 * 获取用户充值子订单列表
 *
 * @author 毛凯
 * @date 2018-3-24
 *
 * @param  orderId	订单总表的主键
 * @param  callback 回调
 *              err 错误信息
 *              result 查询后返回结果
 **/
YjxTradeOrderModel.prototype.getUserPtsOrderSubOrderList = function(orderId,callback){

    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxTradeOrderModel.js [getUserPtsOrderSubOrderList] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql ="	SELECT	" +
            "	  pts.detail_id AS id,	" +
            "	  pts.detail_no AS `no`,	" +
            "	  yg.goods_type AS `type`,	" +
            "	  yg.goods_name AS itemName,	" +
            "	  yg.desc AS itemDesc,	" +
            "	  yg.theme_thumb AS itemThumb,	" +
            "	  yp.show_name AS ppName,	" +
            "	  '' AS docId,	" +
            "	  pts.qty,	" +
            "	  '' AS docName,	" +
            "	  pts.unit,	" +
            "	  pts.update_time	" +
            "	FROM	" +
            "	  yjx.yjx_trade_odr_dtl_pts pts,	" +
            "	  yjx.yjx_uni_items yui,	" +
            "	  yjx.yjx_goods yg,	" +
            "	  yjx.yjx_price yp	" +
            "	WHERE pts.order_id = "+orderId+"	" +
            "	  AND pts.uni_item_id = yui.uni_item_id	" +
            "	  AND item_id = yg.goods_id	" +
            "	  AND pts.del_flg = 0	" +
            "	  AND yp.price_id = pts.price_id ";

        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxTradeOrderModel.js [getUserPtsOrderSubOrderList] queryErr' + queryErr)
            }
            return callback(queryErr, results);
        });
    });
};


/**
 * 获取总订单列表 (多子订单时按位与,即累加): 2[去水印订单],4[秒杀订单],8[vip订单],16[待定]
 *
 * @author 毛凯
 * @date 2017-11-20
 *
 * @param userId 用户唯一标识
 * @param pageNum 页数
 * @param pageSize 每页显示个数
 * @param payType 支付方式
 * @param state 订单状态:10待支付、11已支付、12支付失败、20制作中、30配送中、40完成、50取消
 * @param callback
 *              err 错误信息
 *              result 查询后结果
 *
 **/
YjxTradeOrderModel.prototype.getAllOrder = function(userId,pageNum,pageSize,state,payType,callback){
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxTradeOrderModel.js [getAllOrder] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql = findOrderSql(false, userId,pageNum,pageSize,state,payType);
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxTradeOrderModel.js [getAllOrder] queryErr' + queryErr)
            }
            return callback(queryErr, results);
        });
    });
};


/**
 * 获取总订单数量 (多子订单时按位与,即累加): 2[去水印订单],4[秒杀订单],8[vip订单],16[待定]
 *
 * @author 毛凯
 * @date 2017-11-20
 *
 * @param userId 用户唯一标识
 * @param pageNum 页数
 * @param pageSize 每页显示个数
 * @param payType 支付方式
 * @param state 订单状态:10待支付、11已支付、12支付失败、20制作中、30配送中、40完成、50取消
 * @param callback
 *              err 错误信息
 *              result 查询后结果
 *
 **/
YjxTradeOrderModel.prototype.getOrderCnt =function(userId,pageNum,pageSize,state,payType,callback) {

    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxTradeOrderModel.js [getOrderCnt] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql = findOrderSql(true, userId,pageNum,pageSize,state,payType);
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxTradeOrderModel.js [getOrderCnt] queryErr' + queryErr)
                return callback(queryErr, null);
            }
            if (results && results[0]) {
                return callback(queryErr, results[0].count);
            }
            return callback(queryErr,null);
        });
    });

};


/**
 * 获取用户订单详情
 *
 * @author 毛凯
 * @date 2017-11-20
 *
 * @param userId 用户唯一标识
 * @param orderId 订单唯一标识
 * @param callback
 *              err 错误信息
 *              result 查询后结果
 *
 **/
YjxTradeOrderModel.prototype.getAllOrderList = function(userId,orderId,callback){
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxTradeOrderModel.js [getAllOrder] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql ="	SELECT	" +
            "	  yto.order_id AS id,	" +
            "	  yto.order_no AS `no`,	" +
            "	  yto.odr_type AS `type`,	" +
            "	  yto.state AS state,	" +
            "	  yto.desc AS `name`,	" +
            "	  yto.total_fee AS totalFee,	" +
            "	  yto.discount_fee AS discountFee,	" +
            "	  yto.coupon_fee AS couponFee,	" +
            "	  yto.pay_type AS payType,	" +
            "	  yto.total_cost_pts AS totalPoints,	" +
            "	  DATE_FORMAT(	" +
            "	    yto.finish_time,	" +
            "	    '%Y-%m-%d %H:%i:%S'	" +
            "	  ) AS doneTime,	" +
            "	  yto.odr_dtl_type_tag,	" +
            "	  p.his_id AS pay_his_id,	" +
            "	  CASE	" +
            "	    WHEN p.pay_platform = 10	" +
            "	    THEN p.pay_info21	" +
            "	    WHEN p.pay_platform = 30	" +
            "	    THEN p.pay_info4	" +
            "	    ELSE ''	" +
            "	  END AS thirdOrderNo,	" +
            "       yto.create_time,   " +
            "	  DATE_FORMAT(	" +
            "	    yto.create_time,	" +
            "	    '%Y-%m-%d %H:%i:%S'	" +
            "	  ) AS createTime	" +                 // add by wangjun 增加创建时间返回值 2018-03-07
            "	FROM	" +
            "	  yjx.yjx_trade_order yto	" +
            "	  LEFT JOIN yjx.yjx_payment_his p	" +
            "	    ON p.del_flg = 0	" +
            "	    AND p.pay_platform = yto.pay_platform	" +
            "	    AND p.trade_obj_id = yto.order_id	" +
            "	    AND p.trade_obj_no = yto.order_no	" +
            "	WHERE yto.user_id = "+userId+ "	" +
            "	  AND yto.order_id = "+orderId+"" +
            "	  AND yto.hide = 0	" +
            "	  AND yto.del_flg = 0	" +
            "   ORDER BY yto.create_time DESC ";
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxTradeOrderModel.js [getAllOrder] queryErr' + queryErr)
            }
            return callback(queryErr, results);
        });
    });
};

/**
 * 根据用户唯一标识和统一作品 id, 更新用户订单状态为完成
 *
 * @author 王俊
 * @date 2017-12-2
 *
 * @param userId        用户 id
 * @param uniDocId      统一作品 id
 * @param callback      回调
 *             err:     更新失败
 */
YjxTradeOrderModel.prototype.updateUserWmOrderStateToCompleteByUinDocId = function (userId, uniDocId, callback) {
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxTradeOrderModel.js [getAllOrder] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql = ' UPDATE yjx.yjx_trade_order yto, ' +
            '        yjx.yjx_trade_odr_dtl_wm ytod ' +
            ' SET yto.state = 40, ' +
            '     ytod.state = 40, ' +
            '     yto.finish_time = sysdate(), ' +
            '     yto.update_by = '+ userId +', ' +
            '     ytod.update_by = '+ userId +', ' +
            '     yto.update_time = SYSDATE(), ' +
            '     ytod.update_time = SYSDATE() ' +
            ' WHERE ytod.uni_doc_id = ' + uniDocId +
            '   AND ytod.del_flg = 0 ' +
            '   AND yto.state = 11 ' +  // 支付成功的才能改
            '   AND yto.order_id = ytod.order_id ' +
            '   AND yto.user_id = ' + userId +
            '   AND yto.del_flg = 0 ';
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxTradeOrderModel.js [updateUserWmOrderStateToCompleteByUinDocId] queryErr' + queryErr)
            }
            return callback(queryErr, results);
        });
    });

};

/**
 * 创建水印订单前先取消相同userId与docId并且状态为0,10,12的重复订单
 *
 * @author 毛凯
 * @date 2017-12-13
 *
 * @param userId 用户唯一标识
 * @param docId  用户统一作品id
 * @return null
 *
 **/
YjxTradeOrderModel.prototype.updateUserOdrWmBefore = function (userId, docId, callback) {
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxTradeOrderModel.js [updateUserOdrWmBefore] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql = "  UPDATE  "  +
                    "  	 yjx.yjx_trade_odr_dtl_wm todwm,  "  +
                    "  	 yjx.yjx_trade_order yto  "  +
                    "  SET  "  +
                    "  	 todwm.state = 50,  "  +
                    "  	 yto.state = 50  "  +
                    "  WHERE todwm.uni_doc_Id = "+docId+"  "  +
                    "  	 AND yto.user_id = "+userId+"  "  +
                    "  	 AND yto.order_id = todwm.order_id  "  +
                    "  	 AND yto.del_flg = 0  "  +
                    "  	 AND todwm.del_flg = 0  "  +
                    "  	 AND yto.state IN (0, 10, 12)  "  ;
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxTradeOrderModel.js [updateUserOdrWmBefore] queryErr' + queryErr)
            }
            return callback(queryErr, results);
        });
    });
};

// 获取订单中的用户作品信息
// orderIds: [12,343,1232]
YjxTradeOrderModel.prototype.getOrderUserDocInfo = function (userId, orderIds, callback) {

    var strIds='';
    if(orderIds && (orderIds instanceof Array) && orderIds.length>0) {
        strIds = orderIds.join(',');
    } else {
        return callback('NG', null);
    }

    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxTradeOrderModel.js [getOrderUserDocInfo] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql = " SELECT x.* FROM ( " +
            " select o.order_id, o.order_no, wm.detail_id " +
            "       ,dud.doc_id, dud.uni_doc_id, dud.design_id " +
            "       ,dud.data, dud.ver, 10 AS design_type " +
            " from yjx.yjx_trade_order o, " +
            "      yjx.yjx_trade_odr_dtl_wm wm, " +
            "      yjx.yjx_design_user_doc dud " +
            " where o.del_flg=0 " +
            " AND o.order_id IN (" + strIds + ") " +
            " AND wm.del_flg=0 AND wm.order_id=o.order_id " +
            " AND dud.del_flg=0 AND dud.uni_doc_id=wm.uni_doc_id " +
            " union all " +
            " select o.order_id, o.order_no, wm.detail_id " +
            "       ,vud.doc_id, vud.uni_doc_id, vud.design_id " +
            "       ,vud.tg_data AS data, 3 AS ver, 30 AS design_type " +
            " from yjx.yjx_trade_order o, " +
            "      yjx.yjx_trade_odr_dtl_wm wm, " +
            "      yjx.yjx_video_user_doc vud " +
            " where o.del_flg=0 " +
            " AND o.order_id IN (" + strIds + ") " +
            " AND wm.del_flg=0 AND wm.order_id=o.order_id " +
            " AND vud.del_flg=0 AND vud.uni_doc_id=wm.uni_doc_id " +
            " ) x ORDER BY x.order_id, x.detail_id ";

        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();

            if (queryErr) {
                console.log('YjxTradeOrderModel.js [getOrderUserDocInfo] queryErr' + queryErr)
            }
            return callback(queryErr, results);
        });
    });
};

// 获取订单明细的积分收支信息
YjxTradeOrderModel.prototype.getOdrDtlBalPtsInfo = function(orderId, callback) {

    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxTradeOrderModel.js [getOdrDtlPtsInfo] getConErr' + getConErr);
            return callback(getConErr, null);
        }

        var sql = " SELECT x.* "+
            " FROM ( "+
            "   SELECT 1 AS bal_flg, t1.add_pts AS bal_pts, 16 AS odr_dtl_type, t1.detail_id, 1 AS pay_type, t1.`desc`, t1.create_time "+
            "   FROM yjx_trade_odr_dtl_pts t1 "+
            "   WHERE t1.del_flg=0 AND t1.order_id="+orderId+
            "       UNION ALL "+
            "   SELECT 2 AS bal_flg, t2.cost_pts AS bal_pts, 2 AS odr_dtl_type, t2.detail_id, t2.pay_type, t2.`desc`, t2.create_time "+
            "   FROM yjx_trade_odr_dtl_wm t2 "+
            "   WHERE t2.del_flg=0 AND t2.order_id="+orderId+
            "       UNION ALL "+
            "   SELECT 2 AS bal_flg, t3.cost_pts AS bal_pts, 8 AS odr_dtl_type, t3.detail_id, t3.pay_type, t3.`desc`, t3.create_time "+
            "   FROM yjx_trade_odr_dtl_vip t3 "+
            "   WHERE t3.del_flg=0 AND t3.order_id="+orderId+
            " ) x "+
            " ORDER BY x.bal_flg, x.create_time ";

        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();

            if (queryErr) {
                console.log('YjxTradeOrderModel.js [getOdrDtlPtsInfo] queryErr' + queryErr)
            }
            return callback(queryErr, results);
        });
    });
};


//--------------------------------------------------------------------------------------
// 导出
module.exports = YjxTradeOrderModel;